package org.shean.app.rssreader.services;

import org.shean.app.rssreader.R;
import org.shean.app.rssreader.SzRSSChannelTabActivity;
import org.shean.app.rssreader.provider.SzRSSReader;
import org.shean.app.rssreader.utils.ChannelSource;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteException;

public class RSSRefreshService extends Service {
	NotificationManager mNM;

	@Override
	public void onCreate() {
		mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

		// show the icon in the status bar
		// showNotification();

		// Start up the thread running the service. Note that we create a
		// separate thread because the service normally runs in the process's
		// main thread, which we don't want to block.
		Thread thr = new Thread(null, mTask, "RSSRefreshService");
		thr.start();
	}

	Runnable mTask = new Runnable() {
		public void run() {
			
			synchronized (mBinder) {
				String[] cols = new String[] { SzRSSReader.Channels._ID,
						SzRSSReader.Channels.LINK};
				Cursor c = RSSRefreshService.this.getContentResolver().query(SzRSSReader.Channels.CONTENT_URI, cols, null, null, null);
				
				if(c != null && c.getCount() > 0)
				{
					int totel_unread = 0;
					c.moveToFirst();
					do
					{
						long id = c.getLong(c.getColumnIndexOrThrow(SzRSSReader.Channels._ID));
						String url = c.getString(c.getColumnIndexOrThrow(SzRSSReader.Channels.LINK));
						
						Intent i = new Intent("org.shean.rssreader.action.START_REFRESH");
				        i.putExtra("rss_id", id);
				        sendBroadcast(i);
				        
				        Cursor unread = RSSRefreshService.this.getContentResolver().query(
								ContentUris.withAppendedId(
										SzRSSReader.Posts.CONTENT_URI_LIST, id),
								new String[] { SzRSSReader.Posts._ID }, "read=0", null, null);

						int org_unreadCount = unread.getCount();

						
						try {
							new ChannelSource(RSSRefreshService.this).syncDB(id, url);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
						Intent end_i = new Intent("org.shean.rssreader.action.END_REFRESH");
						end_i.putExtra("rss_id", id);
				        sendBroadcast(end_i);
				        
				        unread.requery();
				        int new_unreadCount = unread.getCount();
				        if(new_unreadCount  >org_unreadCount)
				        	totel_unread += new_unreadCount - org_unreadCount;
				        unread.close();
					}
					while(c.moveToNext());
					
					if(totel_unread > 0)
					{
						showNotification(totel_unread);
					}
				}
				
				c.close();
			}

			
			// Done with our work... stop the service!
			RSSRefreshService.this.stopSelf();
		}
	};

	@Override
	public IBinder onBind(Intent intent) {
		return mBinder;
	}

	/**
	 * Show a notification while this service is running.
	 */
	private void showNotification(int num) {
		// // In this sample, we'll use the same text for the ticker and the
		// expanded notification
		//CharSequence text = getText(R.string.alarm_service_started);
		//
		// // Set the icon, scrolling text and timestamp
		String text = "You have " + num + " post(s) received." ;
		Notification notification = new Notification(R.drawable.notification,text, System.currentTimeMillis());
		//
		// // The PendingIntent to launch our activity if the user selects this
		// notification
		Intent msg = new Intent(this, SzRSSChannelTabActivity.class);
		msg.putExtra("Notification", true);
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0, msg, 0);
		//
		// // Set the info for the views that show in the notification panel.
		notification.setLatestEventInfo(this, "New Posts", text, contentIntent);
		//
		// // Send the notification.
		// // We use a layout id because it is a unique number. We use it later
		// to cancel.
		 mNM.notify(R.string.rss_refresh_service, notification);
	}

	/**
	 * This is the object that receives interactions from clients. See
	 * RemoteService for a more complete example.
	 */
	private final IBinder mBinder = new Binder() {
		@Override
		protected boolean onTransact(int code, Parcel data, Parcel reply,
				int flags) throws RemoteException {
			return super.onTransact(code, data, reply, flags);
		}
	};

}
